<?php
/*******************************************************************************

    FinalsClub.org is a platform for students and faculty to collaborate
    and share their knowledge with the world.

    Copyright (C) 2009  Andrew Magliozzi

    This file is a part of FinalsClub.org.

    FinalsClub.org is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    To contact FinalsClub.org, send an email to info@finalsclub.org, or
    send mail to Finals Club, c/o Veritas Tutors, 1132 Massachusetts Avenue,
    Cambridge, MA 02138.

*******************************************************************************/

/**
 * courses actions.
 *
 * @package    FinalsClub
 * @subpackage courses
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
 */
class coursesActions extends sfActions {

	public function executeIndex(sfWebRequest $request) {
		$network_id = $request->getParameter('network_id');
		$semester_id = $request->getParameter('semester_id');
		$subject_id = $request->getParameter('subject_id');
		
		//$subjects_pager = SubjectPeer::retrievePager(1, 20, $network_id != null ? $network_id : $this->getUser()->getNetworkId());
		$subjects_pager = SubjectPeer::retrieveByNotesPager(1, 20, $network_id != null ? $network_id : $this->getUser()->getNetworkId());
		$this->subjects = $subjects_pager->getResults();
		
		$page = $request->getParameter('page', 1);
		$this->courses_pager = CoursePeer::retrievePublicPager($page, 20, $network_id, $semester_id, $subject_id);
		$this->courses = $this->courses_pager->getResults();
		$this->networks = UserPeer::$networks;
		$this->semesters = SemesterPeer::retrieveAll();
		$this->subjects = SubjectPeer::retrieveAll();
		
		$this->network_id = $network_id;
		$this->semester_id = $semester_id;
		$this->subject_id = $subject_id;		
	}
	
	public function executeNew(sfWebRequest $request) {
		if($request->getParameter('redirect'))
		{
			$this->redirect = $request->getParameter('redirect');
		}
		
		$this->form = new CourseForm(null, array('network_id' => $this->getUser()->getNetworkId()));
	}
	
	public function executeCreate(sfWebRequest $request) {
		
		
		$this->forward404Unless($request->isMethod('post'));
		$courseRequest = $request->getParameter('course');
		
		// manually set the network_id, user_id
		$courseRequest['network_id'] = $this->getUser()->getNetworkId();
		$courseRequest['user_id'] = $this->getUser()->getId();
		$courseRequest['status'] = CoursePeer::APPROVED_STATUS;
		
		$this->form = new CourseForm(null, array('network_id' => $this->getUser()->getNetworkId()));
		$this->form->bind($courseRequest);
		if($this->form->isValid()) {
			$course = $this->form->updateObject();
			$course->save();
			$this->getUser()->setFlash('success', 'Your course has been successfully added and is pending approval.');
			$this->course = $course;
			$this->setTemplate('show');			
		} else {
			$this->setTemplate('new');
		}

		if($request->getParameter('redirect'))
		{
			$this->redirect($request->getParameter('redirect'));
		}
		
	}

	public function executeEdit(sfWebRequest $request) {
		$course = new Course();
		// forward 404 if a course with the id in the request doesn't exist
		$this->forward404Unless($course = CoursePeer::retrieveById($request->getParameter('id')));
		$user_id = $this->getUser()->getId();
		$user = new User();
		$user = UserPeer::retrieveById($user_id);
		$user_network = $user->getNetworkId();
		$course_network = $course->getNetworkId();
		// make sure the user editing the course is in the network
		$this->forward404Unless($user_network == $course_network);
		
		$this->form = new CourseForm($course, array('network_id' => $this->getUser()->getNetworkId()));
		$this->form->setDefault('course_id', $course->getId());
	}
	
	public function executeUpdate(sfWebRequest $request) {
		$this->forward404Unless($request->isMethod('post'));

		$courseRequest = $request->getParameter('course');
		// manually set the network_id, user_id and status
		$courseRequest['network_id'] = $this->getUser()->getNetworkId();
		$courseRequest['user_id'] = $this->getUser()->getId();
		$courseRequest['status'] = CoursePeer::APPROVED_STATUS;
		
		$course = new Course();
		$course_id = $courseRequest['course_id'];
		$course = CoursePeer::retrieveById($course_id);		// get the object from the database

		$this->form = new CourseForm($course, array('network_id' => $this->getUser()->getNetworkId()));

		$this->form->bind($courseRequest);
		if($this->form->isValid()) {
			// check if the instructor e-mail field value has been changed, if so we need to send some e-mail alerts
			$stored_email = $course->getInstructorEmail();
			$form_email = $this->form->getValue('instructor_email');		
			if(!empty($stored_email) && !empty($form_email)) {	// make sure neither is blank
				if(strcmp($stored_email, $form_email) !== 0) {	// if the e-mail addresses are different, send e-mail alerts
					$this->sendEmailAlerts(array('new'=>$form_email, 'old'=>$stored_email), $course);	// send email alerts
				}
			}			

			$course = $this->form->updateObject();				// update the object with the cleaned form values
			$course->save();									// save the object
			$this->getUser()->setFlash('success', 'The course has been successfully updated.');
			$this->course = $course;
			$this->redirect('notes/index?course_id='.$course->getId());
		} else {
			$this->setTemplate('edit');
		}
	}

	public function executeShow(sfWebRequest $request) {
		
	$this->group_id = $request->getParameter('group_id');
		$this->page = $request->getParameter('page', 1);
		$this->course_id = $request->getParameter('id');
		$this->lecture = $request->getParameter('lecture');
		$this->semester_id = $request->getParameter('semester_id', false);
		$this->forward404Unless(($this->course_id or $this->group_id),sprintf("Invalid Request"));
		$this->course = CoursePeer::retrieveByPk($this->course_id);
		
		$this->user = UserPeer::retrieveById($this->getUser()->getId());
		
		
		$user = UserPeer::retrieveById($this->getUser()->getId());
  	
  
	  	//access to upload button
	  	if($user && $user->getNetworkId() == $this->course->getNetworkId())	
	  	{
	  		$this->upload_access = 'yes';
	  	}
	  	else
	  	{
	  		$this->upload_access = 'no';
	  	}
			
	}
	
	public function executeNotesList(sfWebRequest $request) {
	
		$this->page = $request->getParameter('page', 1);
		$this->course_id = $request->getParameter('course_id');
		$this->lecture = $request->getParameter('lecture');
		$this->semester_id = $request->getParameter('semester_id', false);
		$this->forward404Unless(($this->course_id),sprintf("Invalid Request"));

		$this->course = CoursePeer::retrieveByPk($this->course_id);
		$this->notes_pager = NotePeer::retrieveByCourseIdPager($this->course_id, $this->getUser()->getId(), $this->page, 10);	
	}
	
	protected function sendEmailAlerts(array $emails, Course $course) {
		// retrieve the smtp server information from the app.yml
		$smtp_server = sfConfig::get('app_smtp_server');
		$smtp_user = sfConfig::get('app_smtp_user');
		$smtp_password = sfConfig::get('app_smtp_password');
		try
		{
			// Create the mailer
			$connection = new Swift_Connection_SMTP($smtp_server, 465, Swift_Connection_SMTP::ENC_SSL);
			$connection->setUsername($smtp_user);
			$connection->setPassword($smtp_password);
			$mailer = new Swift($connection);  
						  
			// Setup messages and subject line
			$new_message = new Swift_Message('FinalsClub.org E-mail Address Change');	// message to the new e-mail address
			$old_message = new Swift_Message('FinalsClub.org E-mail Address Change');	// message to the old e-mail address
						
			// Some variables we will need for the email body - course name and university name
			$course_name = $course->getName();
						
			$network_id = $course->getNetworkId();
			$network_name = UserPeer::$networks[$network_id];						
			
			$instructor_name = $course->getInstructorName();
			if(empty($instructor_name))
				$instructor_name = false;
			
			$old_email = $emails['old'];
			$new_email = $emails['new'];
						
			// Render message parts - we have two different e-mails to send
			$newMailContext = array('name'=>$instructor_name, 'email'=>$new_email, 'course_name'=> $course_name, 'school_name'=> $network_name);	// to be passed as parameters to the partials
			$oldMailContext = array('name'=>$instructor_name, 'email'=>$old_email, 'course_name'=> $course_name, 'school_name'=> $network_name);	// to be passed as parameters to the partials
						
			$new_message->attach(new Swift_Message_Part($this->getPartial('emailChangeAlertNewHtml', $newMailContext), 'text/html'));		// HTML e-mail body
			$new_message->attach(new Swift_Message_Part($this->getPartial('emailChangeAlertNewPlain', $newMailContext), 'text/plain'));		// Plaintext e-mail body

			$old_message->attach(new Swift_Message_Part($this->getPartial('emailChangeAlertOldHtml', $oldMailContext), 'text/html'));		// HTML e-mail body
			$old_message->attach(new Swift_Message_Part($this->getPartial('emailChangeAlertOldPlain', $oldMailContext), 'text/plain'));		// Plaintext e-mail body
						
			// Set the 'To' and 'From' fields
			$mailer->send($new_message, $new_email, $smtp_user);		// message to the new e-mail address
			$mailer->send($old_message, $old_email, $smtp_user);		// message to the old e-mail address
			$mailer->disconnect();
		}
		catch (Exception $e)
		{
			$this->logMessage($e->getMessage(), 'crit');	// Log the exception as critical
			$this->getUser()->setFlash('warning', 'Failed to initialize mailer!');		// alert the user e-mailing failed
		}
	}
	
	public function executeSelectbox(sfWebRequest $request){
		
		if($request->getParameter('subject_id'))
		{
			$this->courses = CoursePeer::retrieveBySubjectId($request->getParameter('subject_id'));
		}
		else
		{
			$this->courses = CoursePeer::doSelect(new Criteria());
		}
		
	}
	
}